package com.briup.cms.service.impl;

import com.briup.cms.config.ConfigProperties;
import com.briup.cms.exception.CustomerException;
import com.briup.cms.service.IUploadRemoteService;
import com.briup.cms.utils.MessageStatus;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * 远程fastdfs上传服务
 */
@Service
public class FastDFSUploadRemoteServiceImpl implements IUploadRemoteService {
    @Autowired
    private FastFileStorageClient storageClient;

//    @Autowired
//    private ThumbImageConfig thumbImageConfig;

    @Autowired
    private ConfigProperties configProperties;

    @Override
    public List<String> uploadRemoteFile(MultipartFile[] files) throws CustomerException {

        //上传后得到的文件地址
        List<String> paths = new ArrayList<>();

        if (Objects.isNull(files) || files.length==0){
            throw new CustomerException(MessageStatus.ERROR);
        }
        //循环获取files数组中的文件
        Arrays.stream(files).forEach(file -> {
            try {
                if (file.isEmpty()){
                    throw new CustomerException(MessageStatus.ERROR);
                }
                StorePath storePath = storageClient.uploadFile(configProperties.getFastdfsUploadGroupName(),file.getInputStream(),file.getSize(),getSuffix(file));
                paths.add(configProperties.getFastdfsUploadBastPath()+storePath.getFullPath());
            } catch (IOException e) {
                throw new CustomerException(MessageStatus.ERROR);
            }
        });
        return paths;
    }

    private void isImage(MultipartFile file) {
        try{
            BufferedImage bi = ImageIO.read(file.getInputStream());
            if(bi == null){
                throw new CustomerException(MessageStatus.ERROR);
            }
        }catch (IOException e){
            throw  new CustomerException(MessageStatus.ERROR);
        }
    }

    private String getSuffix(MultipartFile file) throws CustomerException {
        String filename = file.getOriginalFilename();
        return Objects.requireNonNull(filename).substring(filename.lastIndexOf(".")+1);
    }

}
